<template>
  <div>
    <div style="display: flex; justify-content: center">
      <el-upload
        ref="upload"
        accept=".docx"
        action="#"
        :show-file-list="false"
        :auto-upload="false"
        :on-change="handleChange"
      >
        <el-button type="primary">导入</el-button>
      </el-upload>

      <el-button type="primary" @click="exportWord" style="margin: 0 10px"
        >导出</el-button
      >
    </div>
    <Editor id="textareaEditor" v-model="content" :init="init" />
    {{ content }}
  </div>
</template>
<script setup>
import { ref } from "vue";
import Editor from "@tinymce/tinymce-vue";
import htmlDocx from "html-docx-fixed/dist/html-docx";
import mammoth from "mammoth";
import saveAs from "file-saver";
import { ElMessageBox, ElMessage } from "element-plus";
let content = ref("");
const uploadFileName = ref("111");

let init = {
  // 配置信息
  selector: "#textareaEditor",
  height: 800,
  min_height: 400,
  language_url: "/tinymce/langs/zh_CN.js", // 中文包的存放路径
  language: "zh_CN",
  skin_url: "/tinymce/skins/ui/oxide",
  content_css: "/tinymce/skins/content/default/content.min.css",
  plugins:
    "preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media code codesample table charmap pagebreak nonbreaking anchor insertdatetime advlist lists wordcount help emoticons autosave autoresize",
  toolbar:
    "code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
    styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
    table image charmap emoticons hr pagebreak print | fullscreen | bdmap indent2em lineheight formatpainter axupimgs",
  // toolbar_mode: 'none',

  // menubar: false,
  // resize: false,
};
const exportWord = async () => {
  const fullHtmlContent = `
      <!DOCTYPE html>
      <html>
        <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        </head>
        <body>
          ${content.value}
        </body>
      </html>
    `;
  const converted = htmlDocx.asBlob(fullHtmlContent);
  saveAs(converted, `${uploadFileName.value}.docx`);
  // const url = URL.createObjectURL(converted);

  // const a = document.createElement("a");
  // a.href = url;
  // a.download = "xxx.docx";
  // document.body.appendChild(a);
  // a.click();

  // // 清理
  // document.body.removeChild(a);
  // URL.revokeObjectURL(url);
};
// 导入 文件上传
function handleChange(file, fileList) {
  if (content.value) {
    ElMessageBox.confirm("编辑器内有内容将会被替换，是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        // 文件数量改变
        uploadFileName.value = file.name;
        var fileObj = file.raw;
        const reader = new FileReader();
        reader.onload = (e) => {
          const arrayBuffer = e.target.result;
          mammoth
            .convertToHtml({ arrayBuffer: arrayBuffer })
            .then(displayResult)
            .done();
        };
        reader.readAsArrayBuffer(fileObj);
        ElMessage({
          type: "success",
          message: "解析成功",
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消",
        });
      });
  } else {
    // 文件数量改变
    uploadFileName.value = file.name;
    var fileObj = file.raw;
    const reader = new FileReader();
    reader.onload = (e) => {
      const arrayBuffer = e.target.result;
      mammoth
        .convertToHtml({ arrayBuffer: arrayBuffer })
        .then(displayResult)
        .done();
    };
    reader.readAsArrayBuffer(fileObj);
    ElMessage({
      type: "success",
      message: "解析成功",
    });
  }
}
function displayResult(result) {
  let html = result.value;
  let newHTML = html
    .replace(//g, "")
    .replace("<h1>", '<h1 style="text-align: center;">')
    .replace(/<table>/g, '<table style="border-collapse: collapse;">')
    .replace(/<tr>/g, '<tr style="height: 30px;">')
    .replace(/<td>/g, '<td style="border: 1px solid pink;">')
    .replace(/<p>/g, '<p style="text-indent: 2em;">');
  htmlToText(newHTML);
}
function htmlToText(html) {
  var input = html.replace(/<script.*?>.*?<\/script>/gi, "");
  const inptValue = input
    .replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi, "")
    .replace(/<[^>]+?>/g, "")
    .replace(/\s+/g, " ")
    .replace(/ /g, " ")
    .replace(/>/g, " ");
  content.value = input; // word内容转html后push到编辑器内
  // console.log(input, '----------', inptValue);
}
</script>
<style scoped></style>
